package com.junyi.guava;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

/**
 * 双向的 Map，可以通过 Value 查找 Key
 * @time: 2022/4/7 17:04
 * @version: 1.0
 * @author: junyi Xu
 */
@Slf4j
public class BiMapMy {


    @Test
    public void test() {
        HashBiMap<String, String> biMap = HashBiMap.create();
        biMap.put("aa", "water");
        biMap.put("bb", "cookie");
        biMap.put("cc", "paper");

        log.info("{}", biMap.get("aa"));

        BiMap<String, String> biMapInverse = biMap.inverse();

        log.info("{}", biMapInverse.get("paper"));

        // 注意，修改反转后的对象，会影响原来的对象
        biMapInverse.put("water", "dd");
        log.info("{}", biMap.toString());

    }

    @Test
    public void test2() {

        HashBiMap<String, String> biMap = HashBiMap.create();
        biMap.put("aa", "water");
        biMap.put("bb", "cookie");
        biMap.put("cc", "paper");
        biMap.put("cc", "mask");        // Key 相同则覆盖
        log.info("{}", biMap.toString());

        try {
            biMap.put("dd", "water");       // 由于 Value 值不可重复，直接 put() 会报错
        } catch (IllegalArgumentException e) {
            log.info("error: ", e);
        }

        biMap.forcePut("dd", "water");      // 可以强制
        log.info("{}", biMap.toString());
    }
}
